<template>
    <div class="app-container">
      <dir class="operation-block">
        <el-row type="flex" justify="end" :gutter="20">
          <el-col :span="10">
      
            <el-button
             
              type="info"
              @click="handleBeforeExportytg()"
            >
              <i class="el-icon-download" />
              导出已通过计划
            </el-button>
          </el-col>  
          <el-col :span="14">
            <!-- <el-input v-model="entSearch.key" placeholder="请输入企业名称" style="width: 100%">
              <el-button slot="append" icon="el-icon-search" @click="searchHandle('ent')" />
            </el-input> -->
            <el-select v-model="entSearch.key" placeholder="请选择企业" clearable @change="entChange('ent')">
              <el-option v-for="item in tableDataTotal" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-col>
          <el-col :span="4" style="float: right">
            <el-input  v-model="search.key" placeholder="请输入搜索的关键字" style="width: 100%">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch(1)" />
            </el-input>
          </el-col>
        </el-row>
      </dir>
      <el-table
        ref="wise-table"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        :row-style="setRowStyle"
        @expand-change="expandChange"
      >
        <el-table-column type="index" width="50" label="序号">
          <template slot-scope="scope">
            <span>{{ scope.row.index }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="item_name" label="计划名" />
        <el-table-column prop="item_guanxian" label="管线名称" />
        <el-table-column prop="item_dwfzdw" label="属地负责单位" />
        <el-table-column prop="item_jhzysj" label="计划时间" />
        <el-table-column prop="sp" label="审批状态" />
        <el-table-column prop="item_dwfzdw" label="所属企业" />
        <el-table-column prop="item_lx" label="项目种类" />
 
        <el-table-column prop="address" label="操作" width="120px">
          <template v-if="!scoped.row.entSpaceId" slot-scope="scoped">
            <el-button type="info" size="small" class="activeBtn" round @click="downloadFn(scoped.row)">报表下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page.p"
        :limit.sync="page.ps"
        @pagination="getList"
      />
      <el-dialog title="下载" :visible.sync="dialog" width="30%">
        <el-form ref="ruleForm" :model="ruleForm" label-width="100px" label-suffix="：">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" type="textarea" :rows="5" placeholder="输入备注内容" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog = false">取 消</el-button>
          <el-button type="primary" @click="downloadSubmitHandle">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { postHandle, downloadHandle } from '../../../../api'
  import { imgPath } from '@/filters'
  export default {
    data() {
      return {
        search: {
            key: '',
            fields: []
        },
        entSearch: {
          key: '',
          fields: ['name']
        },
        proSearch: {
          key: '',
          fields: ['name']
        },
        loading: false,
        tableData: [],
        tableDataTotal: [],
        expanded: false,
        viewData: [],
        dialog: false,
        ruleForm: {
          remark: null,
          entSpaceId: null,
          spaceId: null
        },
        projectOptions: []
      }
    },
    computed: {
      detectionObj() {
        let obj = {}
        if (this.viewData && this.viewData.length > 0) {
          obj = this.viewData.find(item => item.type === 1)
        }
        return obj
      },
      embalmingObj() {
        let obj = {}
        if (this.viewData && this.viewData.length > 0) {
          obj = this.viewData.find(item => item.type === 2)
        }
        return obj
      },
      backfillObj() {
        let obj = {}
        if (this.viewData && this.viewData.length > 0) {
          obj = this.viewData.find(item => item.type === 3)
        }
        return obj
      }
    },
    mounted() {
      this.getEnterpriseData()
      this.getJiHuaData()
    },
    methods: {
        getJiHuaData() {
        this.loading = true
        let params = {
          d: {
            search: this.entSearch
          }
        }
        postHandle(`/api/v1/welder-sbtx-second/project-plan/list`, params)
          .then(res => {
            
            this.tableData= res.result
          
           
          })
          .finally(() => {
            this.loading = false
          })
      },

      // 获取所有企业选择
      getEnterpriseData() {
        this.loading = true
        let params = {
          d: {
            search: this.entSearch
          }
        }
        postHandle(`/api/v1/welder-sbtx-second/enterprise-comb/list`, params)
          .then(res => {
            
            this.tableDataTotal = res.result
          
           
          })
          .finally(() => {
            this.loading = false
          })
      },
     
      expandChange({ children }, expanded) {
        this.expanded = expanded
        if (expanded && children && children.length > 0) {
          children.forEach((item, index, arr) => {
            this.initiateProject(item, result => {
              this.$set(arr[index], 'initiateProject', result)
            })
            this.hotProgram(item, result => {
              this.$set(arr[index], 'hotProgram', result)
            })
            this.inspection(item, result => {
              this.$set(arr[index], 'inspection', result)
            })
            this.hotTicket(item, result => {
              this.$set(arr[index], 'hotTicket', result)
            })
            this.detection(item, result => {
              this.$set(arr[index], 'detail', result)
            })
            this.detectionApproval(item, result => {
              this.$set(arr[index], 'detectionApproval', result)
            })
          })
        }
        if (this.tableDataTotal.length > 0) this.setTableIndex(this.tableDataTotal)
      },
      // -项目发起
      initiateProject({ initiateProjectId }, callBack) {
        postHandle(`/api/v1/welder-sbtx-second/approval-process-comb/initiate-project/${initiateProjectId}`).then(res => {
          callBack(res.result)
        })
      },
      // -方案审批
      hotProgram({ hotId }, callBack) {
        postHandle(`/api/v1/welder-sbtx-second/approval-process-comb/hot-program/${hotId}`).then(res => {
          callBack(res.result)
        })
      },
      // --物资准备
      inspection({ spaceId }, callBack) {
        postHandle(`/api/v1/welder-sbtx-second/approval-process-comb/get-inspection/${spaceId}`).then(res => {
          callBack(res.result)
        })
      },
      // --动火票
      hotTicket({ spaceId }, callBack) {
        postHandle(`/api/v1/welder-sbtx-second/approval-process-comb/get-hotTicket/${spaceId}`).then(res => {
          callBack(res.result)
        })
      },
      // --过程管控
      detection({ spaceId }, callBack) {
        postHandle(`/api/v1/welder-sbtx-second/approval-process-comb/get-detection/${spaceId}`).then(res => {
          callBack(res.result)
        })
      },
      // --过程管控
      detectionApproval({ spaceId }, callBack) {
        postHandle(`/api/v1/welder-sbtx-second/approval-process-comb/get-detection-approval/${spaceId}`).then(res => {
          callBack(res.result)
        })
      },
  
      isActive(row, key, code, value) {
        if (row[key]) {
          if (key === 'detail') {
            return row.detail[code] === value
          }
          if (row[key].detail) {
            return row[key].detail[code] === value
          } else {
            return false
          }
        } else {
          return false
        }
      },
      // 项目发起
      initiateProjectHandle(row, level) {
        if (row && row.initiateProject && row.initiateProject.approvalList) {
          let arr = row.initiateProject.approvalList['1']
          if (arr && arr.length > 0) {
            let obj = arr.find(item => item.level === level)
            if (obj && Object.keys(obj.userInfo).length > 0) {
              return obj.userInfo.username
            } else {
              return ''
            }
          } else {
            return ''
          }
        } else {
          return ''
        }
      },
      // 项目发起
      initiateProjectActive(row) {
        let num = 0
        if (row.initiateProject && row.initiateProject.approvalList) {
          try {
            let arr = row.initiateProject.approvalList['1']
            let x = arr.findIndex(item => item.approvalStatus !== 1)
            if (x !== -1) {
              throw new Error('错误')
            } else {
              num += arr.length
            }
          } catch (e) {
            console.log(e)
          }
          return num
        }
      },
      // 方案审批
      hotProgramHandle(row, group, level) {
        if (row && row.hotProgram.approvalList) {
          let arr = row.hotProgram.approvalList[group]
          if (arr && arr.length > 0) {
            let obj = arr.find(item => item.level === level)
            if (obj && Object.keys(obj.userInfo).length > 0) {
              return obj.userInfo.username
            } else {
              return ''
            }
          } else {
            return ''
          }
        } else {
          return ''
        }
      },
      // 方案审批-active
      hotProgramActiveHandle(row) {
        let num = 0
        if (row.hotProgram && row.hotProgram.approvalList) {
          try {
            let arrKey = Object.keys(row.hotProgram.approvalList)
  
            arrKey.forEach(key => {
              if (key === '3' || key === '5') {
                let x = row.hotProgram.approvalList[key].findIndex(i => i.approvalStatus !== 1)
                if (x !== -1) {
                  throw new Error('error')
                } else {
                  num += 1
                }
              } else {
                if (row.hotProgram.approvalList[key]['0'].approvalStatus === 1) {
                  num += 1
                }
              }
            })
          } catch (e) {
            console.log(e)
          }
  
          return num
        }
      },
      // 项目物资准备
      inspectionHandle(row, group, level) {
        if (row && row.inspection && row.inspection.approvalList) {
          let arr = row.inspection.approvalList[group]
          if (arr && arr.length > 0) {
            let obj = arr.find(item => item.level === level)
            if (obj && Object.keys(obj.userInfo).length > 0) {
              return obj.userInfo.username
            } else {
              return ''
            }
          } else {
            return ''
          }
        } else {
          return ''
        }
      },
      // 项目物资准备-active
      inspectionActive(row) {
        let num = 0
        if (row.inspection && row.inspection.approvalList) {
          try {
            let arrKey = Object.keys(row.inspection.approvalList)
            arrKey.forEach(key => {
              if (key === '1') {
                let x = row.inspection.approvalList[key].findIndex(i => i.approvalStatus !== 1)
                if (x !== -1) {
                  num = x
                  throw new Error('error')
                } else {
                  num = 3
                }
              } else {
                if (row.inspection.approvalList[key]['0'].approvalStatus === 1) {
                  num += 1
                }
              }
            })
          } catch (e) {
            console.log(e)
          }
          return num
        }
      },
      // 动火票
      hotTicketHandle(row, group, level) {
        if (row && row.hotTicket.approvalList) {
          let arr = row.hotTicket.approvalList[group]
          if (arr && arr.length > 0) {
            let obj = arr.find(item => item.level === level)
            if (obj && Object.keys(obj.userInfo).length > 0) {
              return obj.userInfo.username
            } else {
              return ''
            }
          } else {
            return ''
          }
        } else {
          return ''
        }
      },
      // 动火票-active
      hotTicketActiveHandle(row) {
        let num = 0
        if (row.hotTicket && row.hotTicket.approvalList) {
          try {
            let arrKey = Object.keys(row.hotTicket.approvalList)
            arrKey.forEach(key => {
              if (key === '5') {
                let x = row.hotTicket.approvalList[key].findIndex(i => i.approvalStatus !== 1)
                if (x !== -1) {
                  throw new Error('error')
                } else {
                  num += 1
                }
              } else {
                if (row.hotTicket.approvalList[key]['0'].approvalStatus === 1) {
                  num += 1
                }
              }
            })
          } catch (e) {
            console.log(e)
          }
  
          return num
        }
      },
      // 查看大图
      getSrcList(str) {
        if (str.lastIndexOf(';') !== -1) {
          str = str.substring(0, str.length - 1)
        }
        let arr = []
        if (str) {
          arr = str.split(';')
        }
        return arr.map(item => imgPath(item))
      },
      detectionApprovalHandle(row) {
        if (row && row.detectionApproval && row.detectionApproval.detectionList) {
          this.viewData = row.detectionApproval.detectionList
        } else {
          this.viewData = []
        }
      },
      downloadFn({ spaceId, children }) {
        this.ruleForm = {
          remark: null,
          entSpaceId: spaceId,
          spaceId: null
        }
        if (children && children.length > 0) {
          let obj = children.find(item => item.id === this.proSearch.key)
          if (obj && obj.spaceId) {
            this.ruleForm.spaceId = obj.spaceId
          }
        }
        this.dialog = true
      },
      downloadSubmitHandle() {
        let { remark, entSpaceId, spaceId } = this.ruleForm
        let obj = { remark, entSpaceId, spaceId }
        downloadHandle(`/api/v1/welder-sbtx-second/progress-comb/export`, { obj }).then(res => {
          this.dialog = false
          this.exportFileHandle(res)
        })
      },
      // 导出
      exportFileHandle(res) {
        let disposition = res.headers['content-disposition'].split(';')[1]
        let fileName = decodeURI(disposition.split('=')[1])
        let blob = new Blob([res.data], { type: res.data.type })
        let url = URL.createObjectURL(blob)
        let a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', fileName)
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(blob)
      },
      // 模糊搜索
      searchHandle(code) {
        if (code === 'ent') {
          this.tableData = this.tableDataTotal.filter(item => item.name.indexOf(this.entSearch.key) !== -1)
        } else {
          let result = []
          this.tableDataTotal.forEach(item => {
            let arr = item.children.map(children => children.name.indexOf(this.proSearch.key) !== -1)
            if (arr.includes(true)) {
              result.push(item)
            }
            this.tableData = result
          })
        }
      },
      setRowStyle({ row, rowIndex }) {
        if (row.id === this.proSearch.key) {
          return { backgroundColor: '#F3F8FF' }
        }
      },
      entChange(code) {
        
        
      
      },
      // 自定义index
      setTableIndex(arr, index) {
        arr.forEach((item, key) => {
          this.$set(item, 'index', key + 1)
          if (index) {
            item.index = index + '-' + (key + 1)
          }
          if (item.children) {
            this.setTableIndex(item.children, item.index)
          }
        })
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .steps_wrap {
    display: flex;
    align-items: center;
    border: 1px solid #cccccc;
    margin: 0 100px;
  
    li {
      flex: 1;
      padding: 6px 16px;
      border-right: 1px solid #cccccc;
      text-align: center;
      cursor: pointer;
    }
  
    & > li:last-child {
      border: none;
    }
  
    & > span {
      flex: 1;
    }
  
    .highlighted {
      // background: rgba(67, 207, 124, 1);
      background: #1890ff;
      color: #ffffff;
    }
  }
  
  .mr-r-20 {
    margin-right: 20px;
    font-size: 16px;
  }
  
  .active_text-color {
    color: #1890ff;
  }
  
  .mr-r-20 {
    margin-right: 20px;
    font-size: 16px;
  }
  .active_text-color {
    color: #1890ff;
  }
  .image {
    width: 50px;
    height: 50px;
    margin-right: 10px;
  }
  </style>
  